package com.niii.message.service;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.niii.message.mapper.MessageMapper;
import com.niii.message.pojo.Message;
import com.niii.message.pojo.Msg;
import com.niii.message.pojo.WebSocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class messageService {

    @Autowired
    private WebSocketServer webSocketServer;

    @Autowired
    private MessageMapper messageMapper;

    public void send(Msg msg){
        List<String> receiver = msg.getReceiver();

        for(String r : receiver){
            if(WebSocketServer.isExist(r)){
                WebSocketServer.sendMsg(r, JSON.toJSONString(msg));
            }
            else{
                Message message = new Message();

                message.setTitle(msg.getTitle());
                message.setBody(msg.getBody());
                message.setSender(msg.getSender());
                message.setReceiver(r);
                messageMapper.insert(message);
            }

        }


    }
}
